﻿namespace FrameworkCore.Models;

/// <summary>
/// 分页列表接口
/// </summary>
public partial interface IPagedList<T> : IList<T>
{
    /// <summary>
    /// 页索引
    /// </summary>
    int PageIndex { get; }

    /// <summary>
    /// 页大小
    /// </summary>
    int PageSize { get; }

    /// <summary>
    /// 总记录数
    /// </summary>
    int TotalCount { get; }

    /// <summary>
    /// 总页数
    /// </summary>
    int TotalPages { get; }

    /// <summary>
    /// 是否有上一页
    /// </summary>
    bool HasPreviousPage { get; }

    /// <summary>
    /// 是否有下一页
    /// </summary>
    bool HasNextPage { get; }
}


/// <summary>
/// 分页列表
/// </summary>
/// <typeparam name="T">T</typeparam>
[Serializable]
public partial class PagedList<T> : List<T>, IPagedList<T>
{
    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="source">源列表</param>
    /// <param name="pageIndex">页索引</param>
    /// <param name="pageSize">页大小</param>
    /// <param name="totalCount">总记录数</param>
    public PagedList(IList<T> source, int pageIndex, int pageSize, int? totalCount = null)
    {
        // 最小允许的页大小为1
        pageSize = Math.Max(pageSize, 1);

        TotalCount = totalCount ?? source.Count;
        TotalPages = TotalCount / pageSize;

        if (TotalCount % pageSize > 0)
            TotalPages++;

        PageSize = pageSize;
        PageIndex = pageIndex;
        AddRange(totalCount != null ? source : source.Skip(pageIndex * pageSize).Take(pageSize));
    }

    /// <summary>
    /// 页索引
    /// </summary>
    public int PageIndex { get; }

    /// <summary>
    /// 页大小
    /// </summary>
    public int PageSize { get; }

    /// <summary>
    /// 总记录数
    /// </summary>
    public int TotalCount { get; }

    /// <summary>
    /// 总页数
    /// </summary>
    public int TotalPages { get; }

    /// <summary>
    /// 是否有上一页
    /// </summary>
    public bool HasPreviousPage => PageIndex > 0;

    /// <summary>
    /// 是否有下一页
    /// </summary>
    public bool HasNextPage => PageIndex + 1 < TotalPages;
}